<?php

namespace app\admin\controller\performance;

use app\common\controller\Backend;
use app\admin\library\Auth;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\db\exception\BindParamException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;
use think\Session;
/**
 * 提成设置
 *
 * @icon fa fa-circle-o
 */
class Percom extends Backend
{

    /**
     * Percom模型对象
     * @var \app\admin\model\performance\Percom
     */
    protected $model = null;
    protected $shop_model = null;
    protected $shop_id = null;

    public function _initialize()
    {
        //echo '这是我的测试';
        parent::_initialize();
        $this->model = new \app\admin\model\performance\Percom;
        $this->shop_model = new \app\admin\model\wanlshop\Shop;
        $this->ladderModel = new \app\admin\model\performance\Ladder;
        $this->shop_id = Session::get('shop');
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("gtypeList", $this->model->getGtypeList());
        $this->view->assign("i1typeList", $this->model->getI1typeList());
        $this->view->assign("i3typeList", $this->model->getI3typeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 列表(本店方案)
     */
    public function index()
    {
        //dump(Session::get('admin'));
        //当前管理员店铺id
        $_admin = Session::get('adminshop');
        //dump($_admin);
        //当前店铺id
        $shop_id = $this->shop_id;
        //是否显示tab
        $show_tab = 0;
        if($_admin == $shop_id && $shop_id != 1)
        {
            $show_tab = 1;
        }
        //是否显示copy
        $show_copy = 0;
        if($_admin == $shop_id && $shop_id == 1)
        {
            $show_copy = 1;
        }
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                     ->where($where)
                     ->where('shop_id', '=', $shop_id)
                     ->order($sort, $order)
                     ->count();
            $list = $this->model
                    ->where($where)
                    ->where('shop_id', '=', $shop_id)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $list = collection($list)->toArray();
            foreach($list as $key => $value)
            {
                $list[$key]['show_copy'] = $show_copy;
                //查询使用门店数
                $list[$key]['use_shop_count'] = $this->model->where(['pid' => $value['id']])->count();
                //查询管理员信息
                $list[$key]['admin_username'] = Db::name('admin')->where(['id' => $value['admin_id']])->value('username');
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->view->assign('show_tab',$show_tab);
        $this->view->assign('show_copy',$show_copy);
        return $this->view->fetch();
    }

    /**
     * 总部方案
     */
    public function toppercom()
    {
        //当前管理员店铺id
        $_admin = Session::get('adminshop');
        //当前店铺id
        $shop_id = $this->shop_id;
        $cur_shop_id = 1;
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                     ->where($where)
                     ->where('shop_id', '=', $cur_shop_id)
                     ->order($sort, $order)
                     ->count();
            $list = $this->model
                    ->where($where)
                    ->where('shop_id', '=', $cur_shop_id)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $list = collection($list)->toArray();
            foreach($list as $key => $value)
            {
                $exist = $this->model->where(['pid' => $value['id'], 'shop_id' => $shop_id])->find();
                $list[$key]['already_copy'] = $exist && !empty($exist) ? 1 : 0;
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 将方案铺设到商家选择商家
     */
    public function resubmit($ids = null)
    {
        $id_arr = explode(',', $ids);
        $all_ids = [];
        foreach ($id_arr as $key => $value)
        {
            $row = $this->model->get($value);
            if ($row)
            {
                $all_ids[] = $value;
            }
        }
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $ids = $this->request->get('ids');
            if (empty($ids))
            {
                return json([]);
            }
            $shop_ids[] = 1;
            $conditions = [];
            $conditions['id'] = ['not in',$shop_ids];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->shop_model
                     ->where($where)
                     ->where($conditions)
                     ->order($sort, $order)
                     ->count();
            $list = $this->shop_model
                    ->where($where)
                    ->where($conditions)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $ids = implode('-', $all_ids);
        $this->assignConfig("percom_id", $ids);
        return $this->view->fetch();
    }
    /**
     * 方案使用门店/商家
     */
    public function use_shop($id = null)
    {
        if(empty($id))
        {
            $this->error('缺少参数');
            exit();
        }
        if ($this->request->isAjax())
        {
            $shop_id_arr = $this->model->where(['pid' => $id])->column('shop_id');
            if(empty($shop_id_arr))
            {
                $this->error('门店不存在');
                exit();
            }
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $conditions = [];
            $conditions['id'] = ['in', $shop_id_arr];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->shop_model
                 ->where($where)
                 ->where($conditions)
                 ->order($sort, $order)
                 ->count();
            $list = $this->shop_model
                ->where($where)
                ->where($conditions)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->assignConfig("id", $id);
        return $this->view->fetch();
    }
    /**
     * 铺设方案到具体商家
     */
    public function savepercomshop()
    {
        if ($this->request->isAjax())
        {
            $params = $this->request->post();
            if (!isset($params['ids']) || empty($params['ids']) || !isset($params['percom_id']) || empty($params['percom_id']))
            {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $shop_ids = $params['ids'];
            $percom_id = $params['percom_id'];
            $percom_ids = explode('-', $percom_id);
            if (count($shop_ids) == 0 || count($percom_ids) == 0)
            {
                $this->error('没有可操作的数据');
            }
            $data_array = [];
            foreach ($percom_ids as $key => $value)
            {
                //查询方案信息
                $row = $this->model->get($value);
                if (!$row)
                {
                    continue;
                }
                $row = $row->toArray();
                $row['conditions'] = json_decode($row['conditions'], true);
                $conditions = $row['conditions'];
                //dump($row);
                //查询自己是否已经添加过
                $exist_shop_ids = $this->model->where(['pid' => $value])->column('shop_id');
                foreach ($shop_ids as $k_shop => $v_shop)
                {
                    if (in_array($v_shop, $exist_shop_ids))
                    {
                        continue;
                    }else
                    {
                        //是否终止执行
                        $over_run = false;
                        foreach($conditions['all_data'] as $k_all_data => $v_all_data)
                        {
                            foreach($v_all_data['data'] as $key2 => $value2)
                            {
                                if($value2['type'] == 'xiangmu')
                                {
                                    foreach($value2['item'] as $key3 => $value3)
                                    {
                                        //如果是商品/服务
                                        if($value3['scope'] == 'goods')
                                        {
                                            //查询本店的商品是否存在
                                            $theGoods = Db::name('wanlshop_goods_shop')->where(['shop_id' => $v_shop, 'goods_id' => $value3['id']])->find();
                                            if(empty($theGoods))
                                            {
                                                //echo '不存在<br />';
                                                $over_run = true;
                                                //break 4;
                                            }else
                                            {
                                                $conditions['all_data'][$k_all_data]['data'][$key2]['item'][$key3]['id'] = $theGoods['new_goods_id'];
                                            }
                                        }
                                        //如果是卡
                                        if($value3['scope'] == 'card_list')
                                        {
                                            //查询本店的卡
                                            $theCard = Db::name('item_shop')->where(['shop_id' => $v_shop, 'item_id' => $value3['id']])->find();
                                            if(empty($theCard))
                                            {
                                                $over_run = true;
                                            }else
                                            {
                                                $conditions['all_data'][$k_all_data]['data'][$key2]['item'][$key3]['id'] = $theCard['new_goods_id'];
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if($over_run == true)
                        {
                            continue;
                        }else
                        {
                            //获取admin
                            $admin_array = Session::get('admin');
                            $row['conditions'] = json_encode($conditions);
                            $row['pid'] = $row['id'];
                            $row['shop_id'] = $v_shop;
                            $row['createtime'] = time();
                            $row['updatetime'] = time();
                            $row['admin_id'] = $admin_array['id'];
                            unset($row['id']);
                            $data_array[] = $row;
                        }
                    }
                }
            }
            if(count($data_array) <= 0)
            {
                $this->error(__('检查方案是否已添加；店铺商品、服务、卡项是否存在！'));
            }else
            {
                $res_count = $this->model->allowField(true)->saveAll($data_array);
                if(count($res_count) > 0)
                {
                    $this->success('操作成功'.count($res_count).'个方案');
                }else
                {
                    $this->error(__('You have no permission', ''));
                }
            }
        }
    }
    /**
     * 将总部方案添加到本店
     */
    public function resubmittoshop($ids = null)
    {
        if ($this->request->isAjax())
        {
            $row = $this->model->get($ids);
            if (!$row)
            {
                $this->error(__('No Results were found'));
            }
            //当前店铺id
            $shop_id = $this->shop_id;
            //查询自己是否已经添加过
            $exist = $this->model->where(['pid' => $ids, 'shop_id' => $shop_id])->find();
            if ($exist && !empty($exist))
            {
                $this->error(__('当前方案已经添加过了！'));
            }
            $row = $row->toArray();
            $row['conditions'] = json_decode($row['conditions'], true);
            $conditions = $row['conditions'];
            //dump($row);
            //dump($conditions);
            //是否终止执行
            $over_run = false;
            foreach($conditions['all_data'] as $key => $value)
            {
                foreach($value['data'] as $key2 => $value2)
                {
                    if($value2['type'] == 'xiangmu')
                    {
                        foreach($value2['item'] as $key3 => $value3)
                        {
                            //如果是商品/服务
                            if($value3['scope'] == 'goods')
                            {
                                //查询本店的商品是否存在
                                $theGoods = Db::name('wanlshop_goods_shop')->where(['shop_id' => $shop_id, 'goods_id' => $value3['id']])->find();
                                if(empty($theGoods))
                                {
                                    $this->error(__('店铺不存在['.$value3['name'].']商品！'));
                                    $over_run = true;
                                    break 3;
                                }else
                                {
                                    $conditions['all_data'][$key]['data'][$key2]['item'][$key3]['id'] = $theGoods['new_goods_id'];
                                }
                            }
                            //如果是卡
                            if($value3['scope'] == 'card_list')
                            {
                                //查询本店的卡
                                $theCard = Db::name('item_shop')->where(['shop_id' => $shop_id, 'item_id' => $value3['id']])->find();
                                if(empty($theCard))
                                {
                                    $this->error(__('店铺不存在['.$value3['name'].']卡项！'));
                                    $over_run = true;
                                    break 3;
                                }else
                                {
                                    $conditions['all_data'][$key]['data'][$key2]['item'][$key3]['id'] = $theCard['new_goods_id'];
                                }
                            }
                        }
                    }
                }
            }
            if($over_run == true)
            {
                exit();
            }
            //dump($conditions);
            //die();
            //获取admin
            $admin_array = Session::get('admin');
            $row['conditions'] = json_encode($conditions);
            $row['pid'] = $row['id'];
            $row['shop_id'] = $shop_id;
            $row['createtime'] = time();
            $row['updatetime'] = time();
            $row['admin_id'] = $admin_array['id'];
            unset($row['id']);
            $result = $this->model->allowField(true)->save($row);
            if($result === false)
            {
                $this->error(__('You have no permission', ''));
                exit();
            }
            $this->success('操作成功');
        }
    }


     /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        //二开扩展
        //dump($params);
        $params['conditions'] = json_decode($params['conditions'], true);
        //dump($params);
        $params['conditions'] = json_encode($params['conditions']);
        //获取admin
        $admin_array = Session::get('admin');
        $params['admin_id'] = $admin_array['id'];
        //dump($params);
        //die();
             

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['shop_id'] = $this->shop_id;
            $result = $this->model->allowField(true)->save($params);
         
           
					if(isset($params['ladder'])){
						$ladder = [];
                    
						foreach ($params['ladder'] as $item) {
						    $ladder[] = [	
								'percom_id' => $this->model->id,
								'type' => $item['type'],
								'startamount' => $item['startamount'],
                                'endamount' => $item['endamount'],
                                'typesum' => $item['typesum'],
								'createtime' => time(),
							];
						}

                        if(!$this->ladderModel->saveAll($ladder)){
							$result == false;
						}
						
					}

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        $row['conditions'] = json_decode($row['conditions'], true);
        //dump($row);
        $row['ladder'] = $this->ladderModel
        ->where('percom_id', 'in', $ids)
        ->select(); 
        
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        $params['conditions'] = json_decode($params['conditions'], true);
        $params['conditions'] = json_encode($params['conditions']);
        //dump($params);
        //die();
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $params['shop_id'] = $this->shop_id;
            $result = $row->allowField(true)->save($params);

            if(isset($params['ladder']) ){
                 $this->ladderModel
                      ->where('percom_id', 'in', $ids)
                      ->delete();

                $ladder = [];
                foreach ($params['ladder'] as $item) {
                    $ladder[] = [
                        'percom_id' => $ids,//$this->model->id,
                        'type' => $item['type'],
                        'startamount' => $item['startamount'],
                        'endamount' => $item['endamount'],
                        'typesum' => $item['typesum'],
                        'createtime' => time(),
                    ];
                }

                if(!$this->ladderModel->saveAll($ladder)){
                    $result == false;
                }
            }

        Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row['conditions'] = json_decode($row['conditions'], true);
        //dump($row);
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }
    /**
     * 选择项目
     */
    public function select_xiangmu()
    {
        //接收参数
        $params = $this->request->get();
        $use_node_obj = json_decode($params['use_node_obj'], true);
        //dump($use_node_obj);
        if(!empty($params['shop_id']))
        {
            $shop_id = $params['shop_id'];
        }else
        {
            //当前店铺id
            $shop_id = Session::get('shop');
        }
        //查询分类
        $cate_map = [
            'status' => 'normal',
            'pid' => 104,
            'publishing_platform' => ['in', '0,2'],
        ];
        $categorylist = Db::name('wanlshop_category')->where($cate_map)->field('id,name as text')->select();
        foreach($categorylist as $key => $value)
        {
            $categorylist[$key]['id'] = 'category_'.$value['id'];
            $categorylist[$key]['old_id'] = $value['id'];
            $categorylist[$key]['scope'] = 'category';
            $categorylist[$key]['state'] = [
                //匹配我的选中项
                'selected' => in_array('category_'.$value['id'], $use_node_obj['my_node_ids']) ? true : false,
                //匹配其他人选中的就禁止
                'disabled' => in_array('category_'.$value['id'], $use_node_obj['other_node_ids']) ? true : false
            ];
            //查询商品
            $listgoods = Db::name('wanlshop_goods')->where(['gdtype' => 0, 'shop_id' => $shop_id, 'category_id' => $value['id'], 'deletetime' => null])->field('id, title as text')->select();
            foreach($listgoods as $key2 => $value2)
            {
                $listgoods[$key2]['id'] = 'goods_'.$value2['id'];
                $listgoods[$key2]['old_id'] = $value2['id'];
                $listgoods[$key2]['scope'] = 'goods';
                $listgoods[$key2]['state'] = [
                    //匹配我的选中项
                    'selected' => in_array('goods_'.$value2['id'], $use_node_obj['my_node_ids']) ? true : false,
                    //匹配其他人选中的就禁止
                    'disabled' => in_array('goods_'.$value2['id'], $use_node_obj['other_node_ids']) ? true : false
                ];
            }
            $categorylist[$key]['children'] = $listgoods;
        }
        //dump($categorylist);
        //查询服务分类
        $service_cate = Db::name('wanlshop_category')->where(['status' => 'normal', 'pid' => 105, 'publishing_platform' => ['in', '0,2']])->field('id,name as text')->select();
        foreach($service_cate as $key => $value)
        {
            $service_cate[$key]['id'] = 'category_'.$value['id'];
            $service_cate[$key]['old_id'] = $value['id'];
            $service_cate[$key]['scope'] = 'category';
            $service_cate[$key]['state'] = [
                //匹配我的选中项
                'selected' => in_array('category_'.$value['id'], $use_node_obj['my_node_ids']) ? true : false,
                //匹配其他人选中的就禁止
                'disabled' => in_array('category_'.$value['id'], $use_node_obj['other_node_ids']) ? true : false
            ];
            //查询服务
            $service_list = Db::name('wanlshop_goods')->where(['shop_id' => $shop_id, 'gdtype' => 1, 'category_id' => $value['id'], 'deletetime' => null])->field('id, title as text')->select();
            foreach($service_list as $key2 => $value2)
            {
                $service_list[$key2]['id'] = 'goods_'.$value2['id'];
                $service_list[$key2]['old_id'] = $value2['id'];
                $service_list[$key2]['scope'] = 'goods';
                $service_list[$key2]['state'] = [
                    //匹配我的选中项
                    'selected' => in_array('goods_'.$value2['id'], $use_node_obj['my_node_ids']) ? true : false,
                    //匹配其他人选中的就禁止
                    'disabled' => in_array('goods_'.$value2['id'], $use_node_obj['other_node_ids']) ? true : false
                ];
            }
            $service_cate[$key]['children'] = $service_list;
        }
        //查询卡分类
        $card_cate = [
            [
                'id' => 'card_cate_1',
                'old_id' => 1,
                'text' => '有限次卡',
                'scope' => 'card_cate',
                'state' => [
                    //匹配我的选中项
                    'selected' => in_array('card_cate_1', $use_node_obj['my_node_ids']) ? true : false,
                    //匹配其他人选中的就禁止
                    'disabled' => in_array('card_cate_1', $use_node_obj['other_node_ids']) ? true : false
                ]
            ],
            [
                'id' => 'card_cate_2',
                'old_id' => 2,
                'text' => '不限次卡',
                'scope' => 'card_cate',
                'state' => [
                    //匹配我的选中项
                    'selected' => in_array('card_cate_2', $use_node_obj['my_node_ids']) ? true : false,
                    //匹配其他人选中的就禁止
                    'disabled' => in_array('card_cate_2', $use_node_obj['other_node_ids']) ? true : false
                ]
            ],
            [
                'id' => 'card_cate_3',
                'old_id' => 3,
                'text' => '通卡',
                'scope' => 'card_cate',
                'state' => [
                    //匹配我的选中项
                    'selected' => in_array('card_cate_3', $use_node_obj['my_node_ids']) ? true : false,
                    //匹配其他人选中的就禁止
                    'disabled' => in_array('card_cate_3', $use_node_obj['other_node_ids']) ? true : false
                ]
            ],
            [
                'id' => 'card_cate_4',
                'old_id' => 4,
                'text' => '充值卡',
                'scope' => 'card_cate',
                'state' => [
                    //匹配我的选中项
                    'selected' => in_array('card_cate_4', $use_node_obj['my_node_ids']) ? true : false,
                    //匹配其他人选中的就禁止
                    'disabled' => in_array('card_cate_4', $use_node_obj['other_node_ids']) ? true : false
                ]
            ],
            [
                'id' => 'card_cate_5',
                'old_id' => 5,
                'text' => '折扣卡',
                'scope' => 'card_cate',
                'state' => [
                    //匹配我的选中项
                    'selected' => in_array('card_cate_5', $use_node_obj['my_node_ids']) ? true : false,
                    //匹配其他人选中的就禁止
                    'disabled' => in_array('card_cate_5', $use_node_obj['other_node_ids']) ? true : false
                ]
            ]
        ];
        //查询卡列表
        foreach($card_cate as $key => $value)
        {
            $card_list = Db::name('item')->where(['shop_id' => $shop_id, 'type' => $value['old_id'], 'deletetime' => null])->field('id, name as text')->select();
            foreach($card_list as $key2 => $value2)
            {
                $card_list[$key2]['id'] = 'card_list_'.$value2['id'];
                $card_list[$key2]['old_id'] = $value2['id'];
                $card_list[$key2]['scope'] = 'card_list';
                $card_list[$key2]['state'] = [
                    //匹配我的选中项
                    'selected' => in_array('card_list_'.$value2['id'], $use_node_obj['my_node_ids']) ? true : false,
                    //匹配其他人选中的就禁止
                    'disabled' => in_array('card_list_'.$value2['id'], $use_node_obj['other_node_ids']) ? true : false
                ];
            }
            $card_cate[$key]['children'] = $card_list;
        }
        $data = [
            [
                'id' => 'all_-1',
                'old_id' => -1,
                'text' => '所有产品',
                'scope' => 'all',
                'state' => [
                    //匹配我的选中项
                    'selected' => in_array('all_-1', $use_node_obj['my_node_ids']) ? true : false,
                    //匹配其他人选中的就禁止
                    'disabled' => in_array('all_-1', $use_node_obj['other_node_ids']) ? true : false
                ],
                'children' => $categorylist
            ],
            [
                'id' => 'all_-2',
                'old_id' => -2,
                'text' => '所有服务',
                'scope' => 'all',
                'state' => [
                    //匹配我的选中项
                    'selected' => in_array('all_-2', $use_node_obj['my_node_ids']) ? true : false,
                    //匹配其他人选中的就禁止
                    'disabled' => in_array('all_-2', $use_node_obj['other_node_ids']) ? true : false
                ],
                'children' => $service_cate
            ],
            [
                'id' => 'all_-3',
                'old_id' => -3,
                'text' => '所有卡项',
                'scope' => 'all',
                'state' => [
                    //匹配我的选中项
                    'selected' => in_array('all_-3', $use_node_obj['my_node_ids']) ? true : false,
                    //匹配其他人选中的就禁止
                    'disabled' => in_array('all_-3', $use_node_obj['other_node_ids']) ? true : false
                ],
                'children' => $card_cate
            ]
        ];
        $result['core']['data'] = $data;
        $result['plugins'] = ['checkbox']; // 启用复选框插件
        //$result['checkbox']['three_state'] = false;
        //dump($result);
        $result = json_encode($result);
        
        $this->view->assign('result', $result);
        return $this->view->fetch();
    }

    /**
     * 选择职称
     */
    public function select_zhicheng()
    {
        //接收参数
        $params = $this->request->get();
        $use_node_obj = json_decode($params['use_node_obj'], true);
        //查询职称
        $list_data = Db::name('wanlshop_staff_rank')->where(['status' => 'normal'])->field('id, name as text')->select();
        foreach($list_data as $key => $value)
        {
            $list_data[$key]['id'] = 'staff_rank_'.$value['id'];
            $list_data[$key]['old_id'] = $value['id'];
            $list_data[$key]['scope'] = 'staff_rank';
            $list_data[$key]['state'] = [
                //匹配我的选中项
                'selected' => in_array('staff_rank_'.$value['id'], $use_node_obj['my_node_ids']) ? true : false,
                //匹配其他人选中的就禁止
                'disabled' => in_array('staff_rank_'.$value['id'], $use_node_obj['other_node_ids']) ? true : false
            ];
        }
        $data = [
            [
                'id' => 'all_-1',
                'old_id' => -1,
                'text' => '所有职称',
                'scope' => 'all',
                /*'state' => [
                    'disabled' => !empty($use_node_obj['my_node_ids']) || !empty($use_node_obj['other_node_ids']) ? true : false
                ],*/
                'state' => [
                    //匹配我的选中项
                    'selected' => in_array('all_-1', $use_node_obj['my_node_ids']) ? true : false,
                    //匹配其他人选中的就禁止
                    'disabled' => in_array('all_-1', $use_node_obj['other_node_ids']) ? true : false
                ],
                'children' => $list_data
            ]
        ];
        $result['core']['data'] = $data;
        $result['plugins'] = ['checkbox'];
        //dump($result);
        $result = json_encode($result);
        $this->view->assign('result', $result);
        return $this->view->fetch();
    }

    /**
     * 选择支付方式
     */
    public function select_pay()
    {
        //接收参数
        $params = $this->request->get();
        $use_node_obj = json_decode($params['use_node_obj'], true);
        //获取支付方式
        $pay_type = [
            [
                'id' => 'static_pay_0',
                'old_id' => 0,
                'text' => '现金(记账)',
                'scope' => 'static_pay',
                'state' => [
                    //匹配我的选中项
                    'selected' => in_array('static_pay_0', $use_node_obj['my_node_ids']) ? true : false,
                    //匹配其他人选中的就禁止
                    'disabled' => in_array('static_pay_0', $use_node_obj['other_node_ids']) ? true : false
                ]
            ],
            [
                'id' => 'static_pay_1',
                'old_id' => 1,
                'text' => '余额',
                'scope' => 'static_pay',
                'state' => [
                    //匹配我的选中项
                    'selected' => in_array('static_pay_1', $use_node_obj['my_node_ids']) ? true : false,
                    //匹配其他人选中的就禁止
                    'disabled' => in_array('static_pay_1', $use_node_obj['other_node_ids']) ? true : false
                ]
            ],
            [
                'id' => 'static_pay_2',
                'old_id' => 2,
                'text' => '景珍支付',
                'scope' => 'static_pay',
                'state' => [
                    //匹配我的选中项
                    'selected' => in_array('static_pay_2', $use_node_obj['my_node_ids']) ? true : false,
                    //匹配其他人选中的就禁止
                    'disabled' => in_array('static_pay_2', $use_node_obj['other_node_ids']) ? true : false
                ]
            ]
        ];
        //查询支付
        foreach($pay_type as $key => $value)
        {
            $list_data = Db::name('pay')->where(['type' => $value['old_id'], 'status' => 'normal'])->field('id, name as text')->select();
            foreach($list_data as $key2 => $value2)
            {
                $list_data[$key2]['id'] = 'pay_'.$value2['id'];
                $list_data[$key2]['old_id'] = $value2['id'];
                $list_data[$key2]['scope'] = 'pay';
                $list_data[$key2]['state'] = [
                    //匹配我的选中项
                    'selected' => in_array('pay_'.$value2['id'], $use_node_obj['my_node_ids']) ? true : false,
                    //匹配其他人选中的就禁止
                    'disabled' => in_array('pay_'.$value2['id'], $use_node_obj['other_node_ids']) ? true : false
                ];
            }
            $pay_type[$key]['children'] = $list_data;
        }
        $data = [
            [
                'id' => 'all_-1',
                'old_id' => -1,
                'text' => '所有支付方式',
                'scope' => 'all',
                'state' => [
                    //匹配我的选中项
                    'selected' => in_array('all_-1', $use_node_obj['my_node_ids']) ? true : false,
                    //匹配其他人选中的就禁止
                    'disabled' => in_array('all_-1', $use_node_obj['other_node_ids']) ? true : false
                ],
                'children' => $pay_type
            ]
        ];
        $result['core']['data'] = $data;
        $result['plugins'] = ['checkbox'];
        // $result['checkbox']['three_state'] = false;
        //dump($result);
        $result = json_encode($result);
        $this->view->assign('result', $result);
        return $this->view->fetch();
    }

    /**
     * 批量操作
     */
    public function multi($ids = null)
    {
        if (false === $this->request->isPost())
        {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids))
        {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        if (false === $this->request->has('params'))
        {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
        if (empty($values))
        {
            $this->error(__('You have no permission'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        //dump($values);
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
            foreach ($list as $item)
            {
                $count += $item->allowField(true)->isUpdate(true)->save($values);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count)
        {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

}
